package com.qa.music.ui;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.alibaba.fastjson.JSONObject;
import com.qa.music.R;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PlayActivity extends AppCompatActivity {
    private String url1;
    private Handler handler;
    ProgressDialog progressDialog;
    AlertDialog.Builder builder;
    /**
     * 圆圈加载进度的 dialog
     */
    private void showWaiting() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setIcon(R.mipmap.ic_launcher);
        progressDialog.setTitle("提示");
        progressDialog.setMessage("加载中...");
        progressDialog.setIndeterminate(true);// 是否形成一个加载动画  true表示不明确加载进度形成转圈动画  false 表示明确加载进度
        progressDialog.setCancelable(false);//点击返回键或者dialog四周是否关闭dialog  true表示可以关闭 false表示不可关闭
        progressDialog.show();
    }

    private void show() {

        builder = new AlertDialog.Builder(this).setIcon(R.mipmap.ic_launcher).setTitle("提示")
                .setMessage("音乐正在下载中,请到系统设置的下载管理查看下载详情!").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
        builder.create().show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_play);

        VideoView videoView = findViewById(R.id.videoView);
        videoView.setKeepScreenOn(true);
        String id = getIntent().getStringExtra("id");
        String name = getIntent().getStringExtra("name");

        TextView textView = findViewById(R.id.textView);
        textView.setText(name);

        String url = "https://music.2hakeji.com/musicdetails";
        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody formBody = new FormBody.Builder()
                .add("id", id)
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Uri uri = Uri.parse(url1);
                videoView.setVideoURI(uri);
                videoView.start();
            }
        };
        showWaiting();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                JSONObject jsonObject = JSONObject.parseObject(string);
                url1 = jsonObject.getString("wma");
                Message msg = new Message();
                handler.sendMessage(msg);
                progressDialog.cancel();
            }

        });


        Button breakbutton = findViewById(R.id.button3);
        breakbutton.setOnClickListener((View v) -> {
            finish();
        });

        Button d = findViewById(R.id.button);
        d.setOnClickListener((View v) -> {
            downLoad(this, url1,name);
        });

    }

    public void downLoad(Context context, String url,String name) {
        Uri uri = Uri.parse(url);        //下载连接
        DownloadManager systemService = (DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);//得到系统的下载管理
        DownloadManager.Request request = new DownloadManager.Request(uri);//得到连接请求对象
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);   //指定在什么网络下进行下载，这里我指定了WIFI网络
        request.setDestinationInExternalPublicDir(context.getPackageName() + "/myDownLoad", name+".mp3");  //制定下载文件的保存路径，我这里保存到根目录
        request.setVisibleInDownloadsUi(true);  //设置显示下载界面
        request.allowScanningByMediaScanner();  //表示允许MediaScanner扫描到这个文件，默认不允许。
        request.setTitle(name);      //设置下载中通知栏的提示消息
        request.setDescription(name);//设置设置下载中通知栏提示的介绍
        // 7.0以上的系统适配
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            request.setRequiresDeviceIdle(false);
            request.setRequiresCharging(false);
        }
        long downLoadId = systemService.enqueue(request);
        show();


//        Timer timer = new Timer();
//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                DownloadManager.Query query = new DownloadManager.Query().setFilterById(downLoadId);
//                Cursor c = systemService.query(query);
//                if (c.moveToFirst()) {
//
//                    int type = c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS);
//                    System.out.println("type:" + type);
//                    if (type == DownloadManager.STATUS_SUCCESSFUL) {
//                        timer.cancel();
//                        Toast.makeText(getBaseContext(), "下载完毕!", Toast.LENGTH_LONG).show();
//
//                    }
//                }
//
//            }
//        }, 0, 1000);

    }

    private int getDownloadPercent(DownloadManager systemService, long downloadId) {
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor c = systemService.query(query);
        if (c.moveToFirst()) {
            int downloadBytesIdx = c.getColumnIndexOrThrow(
                    DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
            int totalBytesIdx = c.getColumnIndexOrThrow(
                    DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
            long totalBytes = c.getLong(totalBytesIdx);
            long downloadBytes = c.getLong(downloadBytesIdx);
            return (int) (downloadBytes * 100 / totalBytes);
        }
        return 0;
    }


}
